package com.hui.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hui.server.entity.Menu;
import com.hui.server.entity.MenuRole;
import com.hui.server.entity.Position;
import com.hui.server.entity.Role;
import com.hui.server.service.MenuRoleService;
import com.hui.server.service.MenuService;
import com.hui.server.service.RoleService;
import com.hui.server.util.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.support.InterceptingHttpAccessor;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.controller
 * @Author: HUI
 * @CreateTime: 2022-04-08 16:30
 * @Description: 权限管理控制器，管理员的CRUD，菜单CRUD，设置了路径权限，无特殊情况不需要再单独设置接口的权限
 */

@RestController
@RequestMapping("/system/basic/permission")
@Slf4j
public class PermissionsController {

    private RoleService roleService;

    private MenuService menuService;

    private MenuRoleService menuRoleService;


    @Autowired
    public PermissionsController(RoleService roleService, MenuService menuService, MenuRoleService menuRoleService) {
        this.roleService = roleService;
        this.menuService = menuService;
        this.menuRoleService = menuRoleService;
    }

    /*
                    角色CRUD
             */
    @ApiOperation(value = "查询所有角色")
    @GetMapping("/")
    public Result<List<Role>> getAllRoles() {
        log.info("进入查询所有角色信息接口");
        List<Role> list = roleService.list();
        return Result.success(list);
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public Result<?> addRole(@RequestBody Role role) {
        log.info("进入添加角色信息接口");
        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_" + role.getName());
        }
        boolean save = roleService.save(role);
        return save ?
                Result.success("添加成功！")
                : Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "添加失败！");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{rid}")
    public Result<?> deleteRole(@PathVariable Integer rid) {
        log.info("进入添加角色信息接口");
        boolean remove = roleService.removeById(rid);
        return remove ?
                Result.success("删除成功！")
                : Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "删除失败！");
    }


    /*
        这几个控制器方法可以写在其他控制器类中的，不然太臃肿
        1、查询所有菜单
        2、查询角色对应的菜单，只查询 menu 的id
        3、更新角色对应的菜单
     */

    @ApiOperation(value = "获取所有菜单")
    @GetMapping("/menus")
    public Result<?> getAllMenus(){
        log.info("进入查询所有菜单信息接口，查询出父子关系");
        List<Menu> list = menuService.getAllMenus();

        return Result.success(list);
    }




    @ApiOperation("查询某个角色的菜单id")
    @GetMapping("/mid/{rid}")
    public Result<?> getMenuIdsByRoleId(@PathVariable Integer rid){
        log.info("进入根据角色ID查询菜单ID接口，传进来的角色id是：{}",rid);
        Integer[] array = menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid))
                .stream().map(MenuRole::getMid).toArray(Integer[]::new);

        return Result.success(array);

    }


    @ApiOperation(value = "更新角色拥有的菜单")
    @PutMapping("/")
    public Result<?> updateMenuRole(Integer rid,Integer[] mids){
        try {
            return menuRoleService.updateMenuRole(rid,mids);
        } catch (SQLException throwables) {
            log.error("发生了数据库异常，数据库开始回滚：{}",throwables.getMessage());
            return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败");
        }
    }


}
